# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

import functools
import logging

from tornado import gen

from coin.base.config import Config


class BittrexRestOrder(object):
  def __init__(self, http_client, ioloop, logger=None):
    self._http_client = http_client
    self._ioloop = ioloop
    self._logger = logger or logging.getLogger(__name__)
    self.handle_order = lambda order_id, response: None
    self.handle_cancel = lambda response: None

  @gen.coroutine
  def _place_order(self, order_id, symbol, side, price, qty):
    logging.debug('Bittrex place order %s.' % symbol)
    if side == 'buy-limit':
      response = yield self._http_client.get('market/buylimit', {
          'market': symbol, 'quantity': qty, 'rate': price
      })
    else:
      assert side == 'sell-limit'
      response = yield self._http_client.get('market/selllimit', {
          'market': symbol, 'quantity': qty, 'rate': price
      })
    logging.debug('order response: %s %s' % (order_id, response))
    return self.handle_order(order_id, response)

  def place_order(self, order_id: str, symbol: str, side: str, price: str, qty: str):
    self._ioloop.add_callback(
        functools.partial(self._place_order, order_id, symbol, side, price, qty))

  @gen.coroutine
  def _cancel_orders(self, server_order_ids):
    responses = []
    for uuid in server_order_ids:
      response = yield self._http_client.get('market/cancel', {'uuid': uuid})
      responses.append(response)
    return self.handle_cancel(responses)

  def cancel_orders(self, server_order_ids: list):
    assert len(server_order_ids) <= 50
    self._ioloop.add_callback(functools.partial(self._cancel_orders, server_order_ids))
